#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>

#define FDSIZE  128

int main(int argc, char *argv[])
{
    fd_set fdset;
    int fdmax;
    int fdbuf[FDSIZE] = {0};
    char buf[1024] = {0};
    int ret;

    if (argc == 1) {
        printf("your files.\n");
        return 0;
    }

    for (int i = 1; i < argc; i++) {
        fdbuf[i] = open(argv[i], O_RDWR);
        if (fdbuf[i] < 0) {
            printf("failed open file: %s\n", argv[i]);
            return -1;
        }
    }

    fdmax = fdbuf[argc - 1];

    while (1) {
        FD_ZERO(&fdset);

        for (int i = 1; i < argc; i++) {
            FD_SET(fdbuf[i], &fdset);
        }

        ret = select(fdmax + 1, &fdset, NULL, NULL, NULL);
        switch (ret) {
            case -1:
                printf("select error!\n");
                break;
            case 0:
                printf("timeout!\n");
                break;
            default:
                for (int i = 1; i < argc; i++) {
                    if (FD_ISSET(fdbuf[i], &fdset)) {
                        memset(buf, 0, sizeof(buf));
                        read(fdbuf[i], buf, sizeof(buf));
                        printf("ret: %d, file: %s, buf: %s\n", ret, argv[i], buf);
                    }
                }
                break;
        }
    }

    return 0;
}
